/* eslint-disable no-underscore-dangle */
/* eslint-disable prefer-promise-reject-errors */
import io from 'socket.io-client';
import { message } from 'antd';

let proxyUrl = '';
if (process.env.NODE_ENV === 'development') {
  proxyUrl = process.env.PROXY_URL;
}
let socket = '';

export function listen(callback, namespace = '') {
  if (socket === '') {
    try {
      socket = io(`${proxyUrl}/ns`, {
        transports: ['websocket'],
          pingTimeout: 180000,
          pingInterval: 60000

      });
      socket.on('close', (e) => {
        console.error('close',e);
      });
      socket.on('connect', () => {
        callback({
          type: 'connect',
          success: true,
          namespace,
        });
      });

      socket.on('error', error => {
        console.error(error);
      });
      socket.on('disconnect', reason => {
        console.log('disconnect',reason);
        if (reason === 'io server disconnect') {
          // 需要自定义重连规则时启用
        }
        // 没有自定义规则socket会自动重连无需写代码
      });
      // socket.on('reconnect', () => {
      //   callback({
      //     type: 'reconnect',
      //     success: true,
      //     namespace,
      //   });
      // });
    } catch (err) {
      // callback({
      //   type: 'connect',
      //   success: false,
      //   namespace,
      // });
    }
  }
  // 不区分单例的订阅
  // 根据namespace触发特定action
  socket.on('action', async data => {
    if (namespace) {
      // 找到batchId 和 namespace才派发进度
      const result = await window.g_app._store.dispatch({
        type: 'socket/findBatchTask',
        payload: {
          namespace,
          batchId: data.data.batchId,
        },
      });
      // 找到了再派发任务
      if (result) {
        callback({ ...data, namespace });
      }
    } else {
      // 没有指定namespace的为未修改模块依然要派发
      callback({ ...data, namespace });
    }
  });
}

/**
 * 订阅方法
 * @param {object:{
 * type: 'sub',
 * data: {
 * to: batchId 批量任务id
 * }
 * }} params
 */
export function socketChannel(params) {
  return new Promise((resolve, reject) => {
    if (socket === '') {
      reject('No socket connection.');
    } else {
      socket.emit(`action`, params, response => {
        console.log('params: ', params);
        console.log('response: ', response);
        if (response.data.success) {
          resolve(response.data);
        } else if (response.type === 'auth') {
          // eslint-disable-next-line no-underscore-dangle
          window.g_app._store.dispatch({
            type: 'socket/fetchSocketToken',
          });
        } else {
          message.warning(response.data.message);
          reject(response.data.message);
        }
      });
    }
  });
}

export function disconnectSocket() {
  if (socket) {
    socket.disconnect();
  }
}

/**
 * 是否已经建立socket连接
 */
export function isSocketEstablished() {
  return !!socket;
}
